<template>
  <div>
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <van-field
      v-model="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="7"
      placeholder="请输入昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { setUserMessage } from '@/api/user'
export default {
  name: 'NikeName',
  props: {
    name: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      message: this.name
    }
  },
  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      if (this.message.trim() === '') {
        this.$toast('昵称不能为空')
        return
      }
      try {
        await setUserMessage({
          name: this.message
        })
        // 请求成功，关闭弹窗
        this.$emit('close')
        // 更新视图
        this.$emit('update:name', this.message)
        // 请求成功弹窗
        this.$toast.success('更新成功')
      } catch (err) {
        console.log(err)
        this.$toast.fail('更新失败')
      }
    }
  }
}
</script>

<style>
</style>
